import util from 'node:util'
import { exec, spawn } from 'node:child_process'
import colors from 'colors'
import os from 'node:os'
const execute = util.promisify(exec)

const argv = process.argv.slice(2)
const port = Number.parseInt(argv[0])
;(async function () {
  const planform =
    os.platform() /* 'aix' | 'darwin' | 'freebsd' | 'linux' | 'openbsd' | 'sunos' | 'win32' */
  try {
    switch (planform) {
      case 'win32':
        // 执行 netstat 命令获取端口信息
        const netstat = spawn('netstat', ['-ano'])

        // 使用 findstr 过滤端口为 8080 的行
        const findstr = spawn('findstr', [port])

        // 将 netstat 的输出流（stdout）连接到 findstr 的输入流（stdin）
        netstat.stdout.pipe(findstr.stdin)

        // 打印 findstr 的输出
        findstr.stdout.on('data', async (data) => {
          let allPidAry = String(data).split('\r\n')
          if (Array.isArray(allPidAry) && allPidAry.length > 0) {
            allPidAry.forEach(async (item) => {
              let PIDMatch = item.match(/\s+(\d+)$/)
              // console.log('🚀💥💥 ~ PIDMatch: --》》', PIDMatch)
              if (!PIDMatch) return
              const PID = PIDMatch[1]
              if (PID === '0')
                return console.log(colors.yellow(`skip PID ${PID}: ${stdout} `))
              try {
                const { stdout, stderr } = await execute(`TSKILL ${PID}`) //// NOTE: 有管道就失败所以用spawn
                console.log(
                  colors.green(
                    `TSKILL the port: ${port} in PID: ${PID} success: ${stdout} `
                  )
                )
              } catch (error) {
                console.error(colors.red(`TSKILL exec err: ${error.message}`))
              }
            })
          }
        })

        // 捕获错误输出
        netstat.stderr.on('data', (data) => {
          console.error(colors.red(`netstat stderr: ${data}`))
        })

        findstr.stderr.on('data', (data) => {
          console.error(colors.red(`findstr stderr: ${data}`))
        })

        // 监听命令退出事件
        netstat.on('close', (code) => {
          if (code !== 0) {
            console.log(
              colors.yellow(`netstat process exited with code ${code}`)
            )
          }
          findstr.stdin.end()
        })

        findstr.on('close', (code) => {
          if (code !== 0) {
            console.log(
              colors.yellow(`findstr process exited with code ${code}`)
            )
          }
        })
        break
      default:
        break
    }
  } catch (error) {
    console.log(colors.red(error.message))
  } finally {
  }
})()
